﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.Unity;
using System.Data;
using ePlanet.ResourceRequest.Services;
using ePlanet.ResourceRequest.Models;
using ePlanet.SingleWell.Services;
using DreamBuilder.UI.UserControls;
using Wuqi.Webdiyer;
using System.Text;
using ePlanet.ResourceRequest.DataAccess;

namespace Web.Views.ResourceRequestManage
{
    public partial class ResourceRequestWellList : PageBase
    {
        [Dependency]
        public IResourceRequestService m_IResourceRequestService
        {
            get;
            set;
        }

        [Dependency]
        public ISingleWellService m_ISingleWellService
        {
            get;
            set;
        }

        [Dependency]
        public IWellCatalogService m_IWellCatalogService
        {
            get;
            set;
        }

        private string m_CatalogID
        {
            get
            {
                if (string.IsNullOrEmpty(Request.QueryString["wellType"]))
                {
                    return this.m_IWellCatalogService.GetBaseCatalog().WELLCATALOG[0].WELLCATALOGID;
                }
                else
                {
                    return Request.QueryString["wellType"];
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            pagerUndo.PageSizeChanging += new EventHandler(pagerTransfered_PageSizeChanging);
            if (!IsPostBack)
            {
                this.BindSingleWellData();
            }
        }

        protected void pagerTransfered_PageSizeChanging(object sender, EventArgs e)
        {
            pagerUndo.CurrentPageIndex = 1;
            BindSingleWellData();
        }

        private void BindSingleWellData()
        {
            int sum = 0;

            string queryStr = CreateFilterSql().Trim();
            if (queryStr.Equals("1=1"))
            {
                this.gv_SingleWellList.DataSource = null;
                this.gv_SingleWellList.DataBind();
                pagerUndo.RecordCount = sum;
                return;
            }

            //DataTable oDataTable = this.m_ISingleWellService.GetSingleWellDataByWellType(this.m_CatalogID, 0, 1000, out sum, null);
            DataTable oDataTable = this.m_ISingleWellService.QuerySingleWell(queryStr,
                (pagerUndo.CurrentPageIndex - 1) * pagerUndo.PageSize, pagerUndo.PageSize, out sum, null);

            this.gv_SingleWellList.DataSource = oDataTable;
            this.gv_SingleWellList.PageSize = pagerUndo.PageSize;
            this.gv_SingleWellList.DataBind();
            pagerUndo.RecordCount = sum;

        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void pagerUntransfered_PageChanging(object sender, PageChangingEventArgs e)
        {
            pagerUndo.CurrentPageIndex = e.NewPageIndex;
            BindSingleWellData();
        }

        private string CreateFilterSql()
        {
            StringBuilder filterBuilder = new StringBuilder();
            filterBuilder.Append("  1=1  ");

            /*
             * 时间：2013年3月10日 21:26:35
             * 单井不需要档号和全宗号
            //档号
            if (!string.IsNullOrEmpty(this.txtArchiveCode.Text.Trim()) && fieldNameList.Contains("ARCHIVECODE"))
            {
                if (this.ddlArchiveCode.SelectedValue == "1")//等于
                    filterBuilder.AppendFormat(" AND ARCHIVECODE='{0}'   ", this.txtArchiveCode.Text.Trim());
                else
                    filterBuilder.AppendFormat(" AND ARCHIVECODE LIKE '%{0}%'  ", this.txtArchiveCode.Text.Trim());
            }

            //全宗号
            if (!string.IsNullOrEmpty(this.txtQuanzonghao.Text.Trim()) && fieldNameList.Contains("QUANZONGCODE"))
            {
                if (this.ddlQuanzonghao.SelectedValue == "1")//等于
                    filterBuilder.AppendFormat("  AND QUANZONGCODE='{0}'   ", this.txtQuanzonghao.Text.Trim());
                else
                    filterBuilder.AppendFormat("  AND QUANZONGCODE LIKE '%{0}%'  ", this.txtQuanzonghao.Text.Trim());
            }
             */
            //题名
            if (!string.IsNullOrEmpty(this.txtTM.Text.Trim()))
            {
                if (this.ddlTM.SelectedValue == "1")//等于
                    filterBuilder.AppendFormat("  AND DATAFILENAME='{0}'   ", this.txtTM.Text.Trim());
                else
                    filterBuilder.AppendFormat("  AND DATAFILENAME LIKE '%{0}%'  ", this.txtTM.Text.Trim());
            }

            //井号
            if (!string.IsNullOrEmpty(this.txtWellCode.Text.Trim()))
            {
                if (this.ddlWellCode.SelectedValue == "1")//等于
                    filterBuilder.AppendFormat("  AND WELLCODE='{0}'   ", this.txtWellCode.Text.Trim());
                else
                    filterBuilder.AppendFormat("  AND WELLCODE LIKE '%{0}%'  ", this.txtWellCode.Text.Trim().ToUpper());
            }

            //井别
            if (!string.IsNullOrEmpty(this.txtWellType.Text.Trim()))
            {
                if (this.ddlWellType.SelectedValue == "1")//等于
                    filterBuilder.AppendFormat("  AND WELLTYPE='{0}'   ", this.txtWellType.Text.Trim());
                else
                    filterBuilder.AppendFormat("  AND WELLTYPE LIKE '%{0}%'  ", this.txtWellType.Text.Trim());
            }

            //施工措施
            if (!string.IsNullOrEmpty(this.txtWorkType.Text.Trim()))
            {
                if (this.ddlWorkType.SelectedValue == "1")//等于
                    filterBuilder.AppendFormat("  AND WORKMODE='{0}'   ", this.txtWorkType.Text.Trim());
                else
                    filterBuilder.AppendFormat("  AND WORKMODE LIKE '%{0}%'  ", this.txtWorkType.Text.Trim());
            }

            return filterBuilder.ToString();
        }

        protected void BtnSearch_Click(object sender, EventArgs e)
        {
            if (CreateFilterSql().Trim().Equals("1=1"))
            {
                Alert("请输入查询条件");
                return;
            }
            BindSingleWellData();
        }

        protected void btnRequestAccess_Click(object sender, EventArgs e)
        {
            //TODO:添加批量申请操作
            //时间：2013年4月30日 16:02:49
            try
            {
                int i = 0;
                foreach (var item in gv_SingleWellList.SelectItems)
                {
                    if (!this.HasNoExpiredRequest(item.ToString()))
                    {
                        i++;
                        this.ApplyNewRequest(item.ToString());
                    }

                    //Alert("此数据已经有未过期的合法申请，请仔细查看历史申请！");

                }
                Alert(string.Format("成功提交申请{0}条资源！", i));
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }
        }

        private void ApplyNewRequest(string dataId)
        {
            if (!string.IsNullOrEmpty(this.hdExpireDate.Value.Trim()))
            {
                DateTime validPeriod = DateTime.MinValue;
                if (DateTime.TryParse(this.hdExpireDate.Value.Trim(), out validPeriod))
                {
                    if (validPeriod.Date <= DateTime.Now.Date)
                    {
                        throw new Exception("申请期限必须大于当前日期");
                    }
                    ResourceRequestModel model = new ResourceRequestModel();
                    ResourceRequestModel.RESOURCEREQUESTRow row = model.RESOURCEREQUEST.NewRESOURCEREQUESTRow();

                    row.ID = Guid.NewGuid().ToString();
                    row.STATUSID = (decimal)ResourceRequestEnum.NewRequest;
                    row.TEMPUSERID = this.CurrentUser.User_ID;
                    row.VALIDPERIOD = validPeriod;
                    row.WELLDATAID = dataId;
                    row.CANDOWNLOAD = this.hdDownload.Value.Equals("true") ? 1 : 0;
                    row.CANVIEW = this.hdScan.Value.Equals("true") ? 1 : 0;
                    model.RESOURCEREQUEST.AddRESOURCEREQUESTRow(row);
                    this.m_IResourceRequestService.ApplyNewRequest(model);
                }
                else
                {
                    throw new Exception("过期日期不是时间格式");
                }
            }
            else
            {
                throw new Exception("请输入过期时间");
            }
        }

        private bool HasNoExpiredRequest(string dataId)
        {
            return this.m_IResourceRequestService.HasNoExpiredRequest(dataId, this.CurrentUser.User_ID);
        }
    }
}